import React, { Component } from 'react'
import classNames from 'classnames'
import PropTypes from 'prop-types'
import request from '../../utils/request'

export default class Main extends Component {
  static propTypes = {
    list: PropTypes.array,
  }
  async handleDel(id) {
    // 告诉后端删
    await request.delete(`/${id}`)
    // 前端重新获取列表并渲染
    this.props.getList()
  }
  handleChange(id, done) {
    return async () => {
      // 告诉后端修改
      await request.patch(`/${id}`, {
        done,
      })
      // 前端重新获取列表并渲染
      this.props.getList()
    }
  }
  render() {
    const { list } = this.props
    return (
      <section className='main'>
        <input id='toggle-all' className='toggle-all' type='checkbox' />
        <label htmlFor='toggle-all'>Mark all as complete</label>
        <ul className='todo-list'>
          {list.map((item) => (
            <li
              key={item.id}
              className={classNames({
                completed: item.done,
              })}
            >
              <div className='view'>
                <input
                  className='toggle'
                  type='checkbox'
                  checked={item.done}
                  onChange={this.handleChange(item.id, !item.done)}
                />
                <label>{item.name}</label>
                <button
                  className='destroy'
                  onClick={this.handleDel.bind(this, item.id)}
                ></button>
              </div>
              <input
                className='edit'
                value='Create a TodoMVC template'
                onChange={() => {}}
              />
            </li>
          ))}
        </ul>
      </section>
    )
  }
}
